<script lang="ts" setup>
  import { reactive, ref, watch,nextTick } from "vue"
    import { request } from "@/utils/service"
  import { getDepartmentList, updateStatus, deleteAdminById,resetPassword,downloadAdminImportTemplate } from "@/api/employee"
  import { type FormInstance, ElMessage, ElMessageBox } from "element-plus"
  import { usePagination } from "@/hooks/usePagination"
  import { cloneDeep } from "lodash-es"
  import handle from './components/handle.vue'
  import useTable from '@/hooks/useTable'
  import AdminSelect from '@/components/AdminSelect/index.vue'
  import departmentSelect from '@/components/departmentSelect/index.vue'

  const loading = ref<boolean>(false)
  const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
  const dialogVisible = ref<boolean>(false)
  const activeRow = ref<any>()
  const tableData = ref<any>([])
  const searchFormRef = ref<FormInstance | null>(null)
  const searchData = reactive<any>({})

  let fileUploadBtn =ref<any>()

  const getTableData = () => {
    loading.value = true
    getDepartmentList({
      ...paginationData,
      ...searchData
    }).then((res: any) => {
      paginationData.total = res.totalCount
      tableData.value = res.data
    }).catch(() => {
      tableData.value = []
    }).finally(() => {
      loading.value = false
    })
  }

  const { handleSelectionChange,multipleSelection, handleBatchDelete, handleDelete, statusLoading,changeIsEnable,handleBatchResetPW,handleResetPW,handleExport } = useTable({getList:getTableData})

  //关闭操作框
  const closeHandle = () => {
    dialogVisible.value = false
  }

  //操作完成
  const successHandle = () => {
    dialogVisible.value = false
    handleSearch()
  }

  //更新操作按钮
  const handleUpdate = (row: any) => {
    activeRow.value = cloneDeep(row)
    dialogVisible.value = true
  }

  //新增操作按钮
  const handleAdd = () => {
    activeRow.value = {}
    dialogVisible.value = true
  }

  //搜索操作
  const handleSearch = () => {
    paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
  }

  //重置搜索表单
  const resetSearch = () => {
    searchFormRef.value?.resetFields()
    handleSearch()
  }
  watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })


//上传文件之前先判断该文件是否是Excel文件
// 文件上传之前判断
const beforeUPload = (file: any) => {
	const isExcel =
		file.type === 'application/vnd.ms-excel' ||
		file.type ===
		'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
	const isLt2M = file.size / 1024 / 1024 < 20;
	if (!isExcel)
		ElMessageBox({
			title: '温馨提示',
			message: '上传文件只能是 xls / xlsx 格式！',
			type: 'warning',
		});
	if (!isLt2M)
		ElMessageBox({
			title: '温馨提示',
			message: '上传文件大小不能超过 20MB!',
			type: 'warning',
		});
	return isExcel && isLt2M;
};
// 文件数超出提示
const exceedFile = () => {
	ElMessage.warning('最多只能上传一个文件！');
};
// 上传错误提示
const handleError = () => {
	ElMessage.error('导入数据失败，请您重新上传！');
};

//上传成功提示
const handleSuccess = () => {
	ElMessage.success('导入数据成功！');
  nextTick(() => {
      // 清空上传组件的文件列表
      if (fileUploadBtn.value) {
        fileUploadBtn.value.clearFiles();
        // 重置 input 的值，确保下次选择相同文件也能触发
        const input = fileUploadBtn.value.$el.querySelector('input[type="file"]') as HTMLInputElement;
        if (input) {
          input.value = '';
        }
      }
    });
};
// 文件上传
const uploadExcel = async (param: any) => {
	let fileFormData = new FormData();
	fileFormData.append('file', param.file);
	//导入公用人事考勤数据
	await request({//这里的http就是普通的axios实例
		method: 'post',
		url: '/bg/admin/importAdmin',
		headers: { "Content-Type": "multipart/form-data" },
		data: fileFormData
	})
};
</script>

<template>
  <div class="app-container">
    <div class="title-wrapper">员工管理</div>
    <div class="page-main">
      <div shadow="never" class="search-wrapper" v-permission="['departmentuser-search']">
        <div class="search-main">
          <el-form ref="searchFormRef" :inline="true" :model="searchData">
            <el-form-item prop="name" label="姓名">
              <el-input v-model="searchData.name" placeholder="请输入姓名" clearable/>
            </el-form-item>
            <el-form-item prop="parentName" label="所属上级">
              <AdminSelect style="width:200px;" :field="'name'" v-model="searchData.parentAdminId" width="100%"/>
            </el-form-item>
            <el-form-item prop="departmentName" label="所属部门">
              <!-- <roleSelect v-model="searchData.roleId"/> -->
              <departmentSelect style="width:200px;" :field="'name'" v-model="searchData.departmentIds" :multiple="true" width="100%"/>
            </el-form-item>
            <el-form-item prop="status" label="状态">
              <el-select style="width:200px;" clearable v-model="searchData.status" placeholder="请选择">
                <el-option label="启用" :value="0"></el-option>
                <el-option label="禁用" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="search-btn">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </div>
      </div>

      <div class="toolbar-wrapper">
        <el-button type="primary" style="margin-right: 10px;" v-permission="['departmentuser-add']" @click="handleAdd">新增</el-button>
        <el-upload  v-permission="['departmentuser-import']" action="#" class="upload-demo" accept=".xlsx, .xls" :on-exceed="exceedFile" :on-error="handleError"
          :on-success="handleSuccess" :http-request="uploadExcel" :before-upload="beforeUPload" :show-file-list="true"
          :limit="1" ref="fileUploadBtn">
          <el-button type="primary">导入</el-button>
        </el-upload>
        <el-button type="primary" style="margin-left: 10px;" v-permission="['departmentuser-download']" @click="handleExport({}, '/bg/admin/downloadImportTemplate','员工导入模板')">下载导入模版</el-button>
        <!-- v-permission="['account-admin:batchDel']" -->
      </div>
      <div v-loading="loading"  class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column type="index" width="60" label="编号"  />
          <!-- <el-table-column sortable prop="adminId" label="编号"  /> -->
          <el-table-column sortable prop="name" label="姓名"  />
          <el-table-column sortable prop="username" label="手机号"  />

          <el-table-column sortable prop="parentName" label="直属上司"  />
          <el-table-column sortable prop="idCard" label="身份证号码"  />
          <el-table-column sortable prop="departmentName" label="部门"  />
          <el-table-column sortable prop="roleName" label="职务"  />

          <el-table-column sortable prop="status" label="状态" >
            <template #default="scope">
              <!-- {{ scope.row.isEnable }} -->
              <el-switch :disabled="scope.row.username == 'admin'" :loading="statusLoading == scope.row.adminId" v-model="scope.row.isEnable" @change="changeIsEnable(updateStatus, scope.row.adminId, {isEnable:scope.row.isEnable?0:1})"/>
            </template>
          </el-table-column>
          <el-table-column sortable prop="createTime" label="创建时间"  />
          <el-table-column fixed="right" label="操作"  >
            <template #default="scope">
              <el-button v-if="scope.row.username != 'admin'" type="primary"  v-permission="['departmentuser-edit']" text size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button v-if="scope.row.username != 'admin'" type="danger" v-permission="['departmentuser-del']" text size="small" @click="handleDelete(deleteAdminById, scope.row.adminId, scope.row.name)">删除</el-button>
              <el-button v-if="scope.row.username != 'admin'" v-permission="['departmentuser-reset-password']" type="primary" text size="small" @click="handleResetPW(resetPassword, scope.row.adminId, scope.row.name)">重置密码</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>

  <handle
    v-if="dialogVisible"
    :id="activeRow.adminId"
    @success="successHandle"
    @cancel="closeHandle"
    />
</template>

<style lang="scss" scoped>

</style>
